package com.accp.restaurant.controller;


import com.accp.restaurant.dao.PermissionDao;
import com.accp.restaurant.dao.RolepermissionDao;
import com.accp.restaurant.dao.StaffDao;
import com.accp.restaurant.entity.Permission;
import com.accp.restaurant.entity.Staff;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class Login {
    @Autowired
    private StaffDao staffDao;

    @Autowired
    private RolepermissionDao rolepermissionDao;
    @Autowired
    private PermissionDao permissionDao;


    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(Staff staff, Map<String, Object> map, HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        UsernamePasswordToken token = new UsernamePasswordToken(staff.getStaffname(),staff.getStaffpwd());
        String msg = "";
        Staff staff1 = null;
        try {
            subject.login(token);
            staff1 = staffDao.Login(staff.getStaffname());
            List<Permission> list = permissionDao.getAll(staff1.getRole().getRoleid());
            for(Permission p:list){
                System.out.println(p.getPername()+"------------------");
            }
            request.getSession().setAttribute("role",staff1.getRole().getRolename());
            request.getSession().setAttribute("strffname",staff1.getStaffname());
            request.getSession().setAttribute("Permission",list);
        } catch (UnknownAccountException e) {
            msg = "账号不存在！";
        } catch (IncorrectCredentialsException e){
            msg ="密码不正确！";
        }
        map.put("msg",msg);
        if(staff1!=null){
            return "redirect:/Super.jsp";
        }else{
            return "login";
        }
    }
    
    @RequestMapping("/outLogin")
    public String outLog(HttpServletRequest request) {
//        request.getSession().invalidate();
//        SimpleAuthenticationInfo info = null;
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        return "redirect:/login.jsp";
    }


}
